package com.cuiweiyou.vigilesmicrecord.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.cuiweiyou.vigilesmicrecord.util.comm.DateFormatUtil;

/**
 * Created by macpro on 2018/5/28.
 */

public class TimerTextView extends AppCompatTextView {
    public TimerTextView(Context context) {
        super(context);
    }

    public TimerTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TimerTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int sec = (int) msg.obj;
            String duration = DateFormatUtil.milliSecondToHHmmssDuration(sec);
            setText(duration);
        }
    };

    class TimerRunnable implements Runnable {
        boolean isRunnind = true;

        public void stopRunnind() {
            isRunnind = false;
        }

        @Override
        public void run() {
            int second = 0;

            Message message = handler.obtainMessage();
            message.obj = second++;
            handler.sendMessage(message);

            while (isRunnind) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                message = handler.obtainMessage();
                message.obj = second++;
                handler.sendMessage(message);
            }
        }
    }

    TimerRunnable timerRunnable;

    public void startTimer() {
        timerRunnable = new TimerRunnable();
        new Thread(timerRunnable).start();
    }

    public void stopTimer() {
        if (null != timerRunnable) {
            timerRunnable.stopRunnind();
        }
        timerRunnable = null;
    }
}



